<template>
  <div class="message-container">
    <!-- 搜索和筛选区域 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="68px">
      <el-form-item label="消息类型" prop="messageType" style="width: 200px;">
        <el-select v-model="queryParams.type" placeholder="请选择消息类型" clearable>
          <el-option
              v-for="dict in message_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否已读" prop="isRead" style="width: 200px;">
        <el-select v-model="queryParams.isRead" placeholder="请选择是否已读" clearable>
          <el-option
              v-for="dict in is_read"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 骨架屏 -->
    <div v-if="loading" class="message-list">
      <div v-for="i in 4" :key="i" class="message-card skeleton-item">
        <el-skeleton :animated="true">
          <template #template>
            <div class="skeleton-content">
              <el-skeleton-item variant="text" class="skeleton-title"/>
              <el-skeleton-item variant="text" class="skeleton-body"/>
              <el-skeleton-item variant="text" class="skeleton-time"/>
            </div>
          </template>
        </el-skeleton>
      </div>
    </div>

    <!-- 消息列表 -->
    <template v-else>
      <div v-if="filteredMessages.length > 0" class="message-list">
        <transition-group name="list">
          <div
              v-for="message in filteredMessages"
              :key="message.messageId"
              class="message-card"
              :class="{
              'unread-message': message.isRead === '0',
              'hover-effect': hoverIndex === message.messageId
            }"
              @click="handleClickMessage(message)"
              @mouseenter="hoverIndex = message.messageId"
              @mouseleave="hoverIndex = null"
          >
            <div class="unread-indicator" v-if="message.isRead === '0'"></div>

            <div class="message-header">
              <div class="message-meta">
                <span class="message-type">
                  {{ TitleMapping(message.type) }}
                  <el-tag
                      v-if="message.isRead === '0'"
                      type="danger"
                      size="small"
                      class="status-tag"
                  >
                    未读
                  </el-tag>
                </span>
                <span class="sub-type">
                  <el-tag type="info" size="small">
                    {{ SubTypeMapping(message.subType) }}
                  </el-tag>
                </span>
              </div>
              <div class="time-info">
                {{ formatTime(message.sendTime) }}
              </div>
            </div>


            <div class="message-content">
              {{ message.content }}
            </div>

            <div class="card-footer">
              <div class="sender-info">
                <el-icon>
                  <User/>
                </el-icon>
                <span>{{ message.createBy }}</span>
              </div>
              <div class="footer-actions">
                <el-button
                    type="danger"
                    size="small"
                    @click.stop="handleDelete(message.messageId)"
                    class="delete-btn"
                >
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </transition-group>
      </div>
      <el-empty v-else description="暂无相关消息" class="empty-state"/>
    </template>

    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="list"
    />
  </div>
</template>

<script setup>
import {
  computed,
  getCurrentInstance,
  onMounted,
  ref,
  reactive,
  toRefs
} from 'vue'
import {User} from '@element-plus/icons-vue'
import {deleteMessage, getMyInboxMessages} from "@/api/messageCenter/messageCenter.js"
import useUserStore from "@/store/modules/user.js"
import {TypeMapping} from "@/constants/message.js"
import dayjs from 'dayjs'
import {useWebSocketStore} from "@/store/modules/websocket.js";

const websocketStore = useWebSocketStore()

const {proxy} = getCurrentInstance()
const {message_type, is_read} = proxy.useDict("message_type", "is_read")
const userId = useUserStore().id

// 响应式状态
const loading = ref(false)
const searchKeyword = ref('')
const hoverIndex = ref(null)
const MessageList = ref([])
const total = ref(0)
const filterStatus = ref('')
const filterSubType = ref('')

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    type: null,
    isRead: null
  },
})
const {queryParams} = toRefs(data)

// 删除消息
function handleDelete(messageId) {
  deleteMessage(messageId).then(res => {
    list()
  })
}

// 搜索
function handleQuery() {
  queryParams.value.pageNum = 1;
  list();
}

// 重置搜索框
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 映射方法
const TitleMapping = (type) => TypeMapping.MessageType[type] || '未知类型'
const SubTypeMapping = (subType) => TypeMapping.SubType[subType] || '其他类型'
const formatTime = (timeStr) => dayjs(timeStr).format('YYYY-MM-DD HH:mm')

// 过滤逻辑
const filteredMessages = computed(() => {
  const keyword = searchKeyword.value.toLowerCase().trim()

  return MessageList.value.filter(message => {
    // 状态过滤
    if (filterStatus.value && message.isRead !== filterStatus.value) return false

    // 子类型过滤
    if (filterSubType.value && message.subType !== filterSubType.value) return false

    // 关键字搜索
    if (keyword) {
      const searchContent = `
        ${message.content}
        ${message.createBy}
        ${SubTypeMapping(message.subType)}
        ${formatTime(message.sendTime)}
      `.toLowerCase()
      if (!searchContent.includes(keyword)) return false
    }

    return true
  })
})

// 处理消息点击
const handleClickMessage = async (message) => {
  try {
    if (message.isRead === '0') {
      await websocketStore.markMessageRead(message.messageId).then(res => {
        if (res.code === 200) {
          message.isRead = '1'
        }
      })
    }
    proxy.$router.push({
      path: '/message-detail',
      query: {messageId: message.messageId}
    })
  } catch (error) {
    console.error('操作失败:', error)
  }
}

// 加载站内信
function list() {
  loading.value = true
  queryParams.value.params = {}
  getMyInboxMessages(queryParams.value)
      .then(res => {
        MessageList.value = res.rows
        total.value = res.total
      })
      .finally(() => {
        loading.value = false
      })
}

onMounted(() => {
  list()
})
</script>

<style scoped lang="scss">
.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  margin-top: auto; /* 关键属性：使底部始终在卡片最下方 */
  padding-top: 4px;
  border-top: 1px solid #eee;

  .footer-actions {
    display: flex;
    gap: 8px;
    align-self: flex-end; /* 右对齐 */
    margin-top: 8px;
  }

  .delete-btn {
    padding: 5px 12px;
    transform: translateY(2px);
    transition: all 0.2s;

    &:hover {
      transform: translateY(0);
      box-shadow: 0 2px 6px rgba(255, 73, 73, 0.2);
    }
  }
}


.filter-area {
  margin-bottom: 25px;
  display: flex;
  align-items: center;
}

.message-container {
  max-width: 100%;
  margin: 20px auto;
  padding: 0 20px;
}

.message-list {
  display: grid;
  gap: 16px;
}

.message-card {
  position: relative;
  padding: 18px 16px 18px 18px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
  min-height: 160px;

  &.unread-message {
    border-left: 3px solid #ff4d4f;
    background: #fffafa;
  }

  &:hover {
    transform: translateY(-3px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;

  .message-meta {
    display: flex;
    align-items: center;
    gap: 10px;

    .message-type {
      font-weight: 600;
      color: #1a2b5f;
    }

    .status-tag {
      margin-left: 8px;
    }
  }

  .time-info {
    font-size: 0.9em;
    color: #666;
  }
}

.message-content {
  color: #444;
  line-height: 1.6;
  margin-bottom: 12px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.sender-info {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 0.9em;
  color: #666;

  .el-icon {
    font-size: 0.95em;
  }
}

.unread-indicator {
  position: absolute;
  top: 50%;
  left: -8px;
  transform: translateY(-50%);
  width: 8px;
  height: 8px;
  background: #ff4d4f;
  border-radius: 50%;
}

/* 保持原有其他样式 */
.search-input {
  margin-bottom: 30px;
  max-width: 400px;
}

.skeleton-content {
  display: flex;
  width: 100%;
  padding: 20px;
}

.skeleton-title {
  flex: 0 0 160px;
  margin-right: 30px;
}

.skeleton-body {
  flex: 1;
  margin-right: 30px;
}

.skeleton-time {
  flex: 0 0 140px;
}

.list-enter-active,
.list-leave-active {
  transition: all 0.5s ease;
}

.list-enter-from,
.list-leave-to {
  opacity: 0;
  transform: translateY(30px);
}

.empty-state {
  margin-top: 50px;
}
</style>
